import React, {Component} from 'react';
import { Input,Popover} from 'antd';
import { SearchOutlined} from '@ant-design/icons';
import './index.less'
import {withRouter} from 'react-router-dom'
import {searchGoods} from "../../../../network/search";
class Search extends Component {
    state = {
        input: '',
        data: []
    }
    search = (e) => {
        this.setState({
            input: e.target.value
        },async () => {
            if(this.state.input){
                let result = await searchGoods(this.state.input)
                if(result.code === 200){
                    this.setState({
                        data: result.data
                    })
                }
            }
        })
    }
    showContent = () => {
        if(this.state.input){
            return (
                <div className='searchContent'>
                    <ul>
                        {
                            this.state.data.length === 0 ? <div className='noGoods'>未查找到该商品</div> : this.state.data.map(item => {
                                return (
                                    <li key={item.gid} onClick={this.goThis(item.gid)}>
                                        {item.gtitle}
                                    </li>
                                )
                            })
                        }
                    </ul>
                </div>
            )
        }else{
            return (
                <div>请输入商品名称</div>
            )
        }

    }
    goThis = (gid) => {
        return () => {
            this.props.history.push(`/detail?gid=${gid}`)
        }
    }
    render() {
        return (
            <div className='search'>
                {/*弹出气泡*/}
                <Popover placement="bottomLeft" content={this.showContent()} trigger="focus">
                {/*搜索框*/}
                <Input
                    className='searchInput'
                    placeholder="请输入搜索的商品"
                    prefix={<SearchOutlined className="site-form-item-icon"/>}
                    onInput={this.search}
                />
                </Popover>
            </div>
        );
    }
}

export default withRouter(Search);